package com.powernode.config;

import com.powernode.auth2.SmsCodeTokenGranter;
import com.powernode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenEnhancer jwtTokenEnhancer;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

        security
                // oauth/token_key 放开访问
                .tokenKeyAccess("permitAll()")
                // oauth/check_token 放开访问
                .checkTokenAccess("permitAll()")
                // 表单认证申请令牌
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                // 客户端id
                .withClient("app_client")
                // 密码
                .secret(new BCryptPasswordEncoder().encode("juice"))
                //授权模式
                .authorizedGrantTypes("password","sms_code","refresh_token")
                // 授权范围
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        TokenEnhancerChain chain = new TokenEnhancerChain();
        List<TokenEnhancer> tokenEnhancers = new ArrayList<>();

        tokenEnhancers.add(jwtTokenEnhancer);
        tokenEnhancers.add(jwtAccessTokenConverter);

        chain.setTokenEnhancers(tokenEnhancers);

        endpoints
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(chain)
                .tokenGranter(tokenGranter(endpoints))
                .authenticationManager(authenticationManager)
                .userDetailsService(userService);
    }

    private TokenGranter tokenGranter(AuthorizationServerEndpointsConfigurer endpoints) {
        // 获取现有的授权类型
        List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
        // 创建一个自定义授权类型对象
        SmsCodeTokenGranter smsCodeTokenGranter = new SmsCodeTokenGranter(
                                                                    endpoints.getTokenServices(),
                                                                    endpoints.getClientDetailsService(),
                                                                    endpoints.getOAuth2RequestFactory(),
                                                                    userService);
        granters.add(smsCodeTokenGranter);

        return new CompositeTokenGranter(granters);
    }
}
